package org.yunai.swjg.server.module.player.operation;

import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.core.service.OnlineContextService;
import org.yunai.swjg.server.core.service.OnlineState;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.yfserver.async.IIoSerialOperation;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 玩家登出游戏后信息保存操作
 *
 * User: yunai
 * Date: 13-4-26
 * Time: 上午9:28
 */
public class PlayerSaveOperation implements IIoSerialOperation {

    private static OnlineContextService onlineContextService;
    static {
        onlineContextService = BeanManager.getBean(OnlineContextService.class);
    }

    private final Online online;

    public PlayerSaveOperation(Online online) {
        this.online = online;
    }

    @Override
    public State doStart() {
        online.getPlayer().onLogout();
        return State.STARTED;
    }

    @Override
    public State doIo() {
        // TODO 简单点
        Player player = online.getPlayer();
        if (player != null) {
            player.clearScenePreInfo();
            player.save(player); // 最后提交次，为了坐标等一些频繁的更新信息没经常入库。
        }
        online.getDataUpdater().process();
        return State.IO_DONE;
    }

    @Override
    public State doFinish() {
        online.setState(OnlineState.logouting);
        onlineContextService.removeOnline(online.getSession());
        if (online.getUser() != null) {
            onlineContextService.removeUser(online);
            if (online.getPlayer() != null) {
                onlineContextService.removePlayer(online);
            }
        }
        online.setState(OnlineState.logouted);
        return State.FINISHED;
    }

    @Override
    public Integer getSerialKey() {
        return online.getPlayer().getId();
    }
}
